//
//  SPErrorReporter.swift
//  
//
//  Created by LSP on 2021/1/9.
//

import Foundation



class SPError : SPModelBase {
    private static
    var SPERROR_RECORD_ID: Int {
        var id = UserDefaults.standard.integer(forKey: "SPERROR_RECORD_ID_KEY")
        if id == 0 {
            id = 1000
        }
        id += 1
        UserDefaults.standard.set(id, forKey: "SPERROR_RECORD_ID_KEY")
        return id
    }
    
    public var userId: String
    public var message: String
    public var location: String
    public lazy var errorType: Int = 0
    public lazy var internalCode: Int = 10001
    public var creatTime: TimeInterval = {
        return Date.timeStamp
    }()
    public var recordID: Int = {
        return SPERROR_RECORD_ID
    }()
    public var appVersion: String = {
        return APP.VERSION
    }()

    convenience public
    init(userId: String, message msg: String, file: String = #fileID, line: Int = #line, func function: String = #function) {
        var dic = [String: Any]()
        
        dic["userId"] = userId
        dic["location"] = file.replacingOccurrences(of: "/", with: ".") + " in " + function + ":\(line)"
        dic["message"] = msg
        
        self.init(dic:dic)
    }
    
    
    required public init(dic: [String : Any]?) {
        var loc = "..."
        var uid = "-1"
        var msg = "no"
        
        let d = dic ?? [:]
        
        if let o = d["location"] as? String {
            loc = o
        }
        if let o = d["userId"] as? String {
            uid = o
        }
        if let o = d["message"] as? String {
            msg = o
        }
        
        self.location = loc
        self.userId = uid
        self.message = msg
        
        super.init(dic: dic)
        
        if let o = d["errorType"] as? Int {
            self.errorType = o
        }
        if let o = d["internalCode"] as? Int {
            self.internalCode = o
        }
        if let o = d["creatTime"] as? TimeInterval {
            self.creatTime = o
        }
        if let o = d["recordID"] as? Int {
            self.recordID = o
        }
        if let o = d["appVersion"] as? String {
            self.appVersion = o
        }
    }
}
